package cn.fastoo.task;

import cn.fastoo.common.utils.SmsSender;
import cn.fastoo.service.UserService;
import cn.fastoo.utils.ConfigProps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Fastoo Queue
 */
public class FastooMtMessageQueue {

    private final static Logger logger = LoggerFactory.getLogger(FastooMtMessageQueue.class);

    private static UserService userService;

    private static BlockingQueue<MtMessage> blockingQueue = new LinkedBlockingQueue<MtMessage>();

    private static Long UPDATE_INTERVAL = 200L;

    static {
        Consumer consumer=new Consumer(blockingQueue);

        new Thread(consumer,"fastoo_queue").start();

    }

    public static void put(UserService userBaseService,MtMessage mtMessage){
        try {
            userService = userBaseService;
            blockingQueue.put(mtMessage);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //消费者
    public static class Consumer implements Runnable {

        private final BlockingQueue<MtMessage> blockingQueue;

        private volatile boolean flag;

        public Consumer(BlockingQueue<MtMessage> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }
        public void run() {
            while(!flag){

                try {
                    MtMessage mtMessage = blockingQueue.take();

                    String  result = SmsSender.fastooApiSend(ConfigProps.getFastooApiUrl(),mtMessage.getDa(), mtMessage.getMsg(),mtMessage.getApiKey());
                    logger.info("result="+result);
                    //更新提交记录
                    userService.updateSmsrecordStatus(mtMessage.getDa(),mtMessage.getLocalMsgid(),result);


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        public void shutDown(){
            flag=true;
        }
    }





    public static void main(String[] args) throws InterruptedException {

    }
}
